package com.new2i.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.new2i.service.able.ApiService;
import com.new2i.util.XmlUtil;

/**
 * 接口API逻辑处理实现类
 * 
 * @since 2015/09／22
 * @author 2i
 *
 */
@Service("ApiService")
public class ApiServiceImpl implements ApiService{

	private static Logger logger = Logger.getLogger(ApiServiceImpl.class);
	
	@Override
	public List<String> selectApiList() { 
		List<String> list = new ArrayList<String>();  
		String classPath = this.getClass().getClassLoader().getResource("/").getPath();  
		String dirPath = "com/new2i/api/xml"; 
		String fullPath = classPath + dirPath;
		logger.debug("xml full path==>" +fullPath );   
		File dir = new File(fullPath);
		File[] files = dir.listFiles();
		for(File xmlFile : files) {
			String absPath = xmlFile.getAbsolutePath();
			logger.debug("xml file path==>" +absPath ); 
			list.add(absPath);
		}
		return list;
	}

	@Override
	public List<HashMap<String, Object>> getApiInfo(String path) {   
		List<HashMap<String, Object>> apiList =  new ArrayList<HashMap<String, Object>>();
		if(path == null || path.length() <= 0) {
			return apiList;
		}
		List<HashMap<String, String>> list = XmlUtil.parseXmlByFile(path); 
		if(list == null) 
			return apiList;
		for(HashMap<String, String> map : list) { 
			//解析参数和注释
			String params = map.get("params"); 
			String[] paramArray = params.split("&");
			HashMap<String, String> paramMap = new HashMap<String,String>();
			
			if(!(params == null || params.length() <= 0)) {
				for(String param : paramArray) { 
					String paramName = param.substring(0, param.indexOf("="));
					String paramValue = param.substring(param.indexOf("=") + 1);
					paramMap.put(paramName, paramValue); 
				}  
			}
			
			String comments = map.get("comments"); 
			String[] commentArray = comments.split("&"); 
			HashMap<String, String> commentMap = new HashMap<String,String>();
			if(!(comments == null || comments.length() <= 0)) {
				for(String comment : commentArray) { 
					String commentName = comment.substring(0, comment.indexOf("="));
					String commentValue = comment.substring(comment.indexOf("=") + 1);
					commentMap.put(commentName, commentValue); 
				}  
			}
			HashMap<String, Object> apiMap = new HashMap<String, Object>(map);
			apiMap.remove("comments");
			apiMap.put("param_info", paramMap); 
			apiMap.put("comment_info", commentMap);
			apiList.add(apiMap); 
		} 
		return apiList;
	}

}
